package com.yuhf.dbutils;

import com.yuhf.dbutils.exception.AccessDbException;
import lombok.extern.log4j.Log4j;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 获取数据库连接类
 */
@Log4j
public class DBConnection {

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();   //线程本地变量，每个线程都有自己的副本

    private static final String DRIVER_CLASS_NAME;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;
    //静态语句块，在类加载的时候执行，只执行一次,该语句块用于加载数据库驱动类，读取数据库连接信息等操作。
    static {
        Properties prop = new Properties(); //创建一个Properties对象，用于存储数据库连接信息。
        try {
            prop.load(DBConnection.class.getResourceAsStream("/jdbc.properties"));  //从类路径下的jdbc.properties文件中加载数据库连接信息。
        } catch (IOException e) {
            log.error("jdbc.properties file not found,message is" + e.getMessage());
        }
        DRIVER_CLASS_NAME = prop.getProperty("jdbc.driverClassName");   //获取jdbc.driverClassName键的值，即数据库驱动类的全限定名。
        URL = prop.getProperty("jdbc.url");
        USERNAME = prop.getProperty("jdbc.userName");
        PASSWORD = prop.getProperty("jdbc.password");
        try {
            Class.forName(DRIVER_CLASS_NAME);   //加载数据库驱动类。
        } catch (ClassNotFoundException e) {
            log.error("class not found,message is " + e.getMessage());
            throw new AccessDbException("数据库驱动类没有找到");
        }
    }
    //获取数据库连接
    public static Connection getConnection() {
        Connection connection = threadLocal.get();  //从线程本地变量中获取数据库连接。
        try {
            if (null == connection || connection.isClosed()) {
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);  //如果连接不存在或已关闭，则创建一个新的数据库连接。
            }
            threadLocal.set(connection);
        } catch (SQLException e) {
            log.error("create connection error,message is " + e.getMessage());
            throw new AccessDbException("数据库连接创建失败");
        }
        return connection;
    }
    //关闭数据库连接
    public static void closeConnection() {
        Connection connection = threadLocal.get();
        try {
            if (null != connection && connection.getAutoCommit()) { //如果连接存在且自动提交模式为true，则直接关闭连接。
                connection.close();
            }
        } catch (SQLException e) {
            log.error("close connection error,message is " + e.getMessage());
            throw new AccessDbException("数据库连接关闭失败");
        }
    }
}
